package com.momo.configuration;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.util.http.apache.ApacheHttpClientBuilder;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.enums.TicketType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * Created by Kagome on 2019/5/16.
 */
public class WxMpSpringRedisConfigStorage extends WxMpInMemoryConfigStorage {
    private final static String ACCESS_TOKEN_KEY = "wechat_access_token_";

    private final static String JSAPI_TICKET_KEY = "wechat_jsapi_ticket_";

    private final static String CARDAPI_TICKET_KEY = "wechat_cardapi_ticket_";

    private final RedisTemplate<String, String> redisTemplateString;


    private String accessTokenKey;

    private String jsapiTicketKey;

    private String cardapiTicketKey;

    public WxMpSpringRedisConfigStorage(RedisTemplate<String, String> redisTemplateString) {
        this.redisTemplateString = redisTemplateString;
    }

    @Override
    public void setAppId(String appId) {
        super.setAppId(appId);
//        定义redis中存储的名称
        this.accessTokenKey = ACCESS_TOKEN_KEY.concat(appId);
        this.jsapiTicketKey = JSAPI_TICKET_KEY.concat(appId);
        this.cardapiTicketKey = CARDAPI_TICKET_KEY.concat(appId);
    }

    @Override
    public String getAccessToken() {
     String accessTokenKey=   redisTemplateString.opsForValue().get(this.accessTokenKey);
        return accessTokenKey;
    }

    @Override
    public boolean isAccessTokenExpired() {
        return redisTemplateString.getExpire(this.accessTokenKey) < 2;
    }

    @Override
    public synchronized void updateAccessToken(String accessToken, int expiresInSeconds) {
        redisTemplateString.opsForValue().set(this.accessTokenKey, accessToken, expiresInSeconds - 200, TimeUnit.SECONDS);
    }

    @Override
    public void expireAccessToken() {
        redisTemplateString.expire(this.accessTokenKey, 0, TimeUnit.SECONDS);
    }

    @Override
    public String getJsapiTicket() {
        return redisTemplateString.opsForValue().get(this.jsapiTicketKey);
    }

    @Override
    public String getCardApiTicket() {
        return redisTemplateString.opsForValue().get(this.cardapiTicketKey);
    }


}
